package com.lzq.concurrent.lock;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {

    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    private void blockMethod() throws InterruptedException {
        lock.lockInterruptibly();
        try {
            System.out.println("阻塞线程");
            condition.await();
            System.out.println("blockMethod() 被唤醒了");
        } finally {
            lock.unlock();
        }

    }

    private void wakeMethod () throws InterruptedException {
        lock.lockInterruptibly();
        try {
            System.out.println("唤醒线程");
            condition.signal();
//            Thread.sleep(3000); // 此时仍在锁里，会等到这三秒执行完毕
        } finally {
            lock.unlock();
        }
        Thread.sleep(3000); // 已经把锁放开了，会和另外的线程同时运行

    }

    public static void main(String[] args) throws InterruptedException {
        LockTest lockTest = new LockTest();
        new Thread(() -> {
            try {
                lockTest.blockMethod();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        System.out.println("主线程休息 2 秒");
        Thread.sleep(2000);

        new Thread(() -> {
            try {
                lockTest.wakeMethod();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }

}
